package com.dexilaonian.exception;


import com.dexilaonian.utils.Logutil;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;


/**
 * 异常处理的工厂
 * @ author  Huang
 * @ date    2017-04-25 14:25
 */
public class FactoryException {

    private static final String HttpException_MSG = "网络错误";
    private static final String ConnectException_MSG = "连接失败";
    private static final String JSONException_MSG = "fastjeson解析失败";
    private static final String UnknownHostException_MSG = "无法解析该域名";
    private static final String SERVICE_ERROR = "服务器异常";

    /**
     * 解析异常
     */
    public static ApiException analysisExcetpion(Throwable e) {
        ApiException apiException = new ApiException(e);
        if (e instanceof HttpException) {
            //网络异常
            Logutil.e("网络异常");
            HttpException exception = (HttpException) e;
            apiException.setCode(exception.response().code());
            apiException.setDisplayMessage(HttpException_MSG);
        } else if (e instanceof ConnectException || e instanceof SocketTimeoutException) {
             /*链接异常*/
            apiException.setCode(CodeException.HTTP_ERROR);
            apiException.setDisplayMessage(ConnectException_MSG);
        } else if (e instanceof JSONException || e instanceof ParseException) {
            apiException.setCode(CodeException.JSON_ERROR);
            apiException.setDisplayMessage(JSONException_MSG);
            Logutil.e("JSON_ERROR");
        } else if (e instanceof UnknownHostException) {
            /*无法解析该域名异常*/
            apiException.setCode(CodeException.UNKOWNHOST_ERROR);
            apiException.setDisplayMessage(UnknownHostException_MSG);
            Logutil.e("无法解析该域名异常");
        } else {
            /*未知异常*/
            Logutil.e("未知异常");
            apiException.setCode(CodeException.UNKNOWN_ERROR);
            apiException.setDisplayMessage(SERVICE_ERROR);
        }
        return apiException;
    }
}
